package com.example.demo.service;

import com.example.demo.dao.RoleMapper;
import com.example.demo.dao.UserRoleMapper;
import com.example.demo.entity.Role;
import com.example.demo.entity.UserRole;
import com.example.demo.pojo.BSResult;
import com.example.demo.utils.BSResultUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<Role> findAllRoles() {
        return roleMapper.selectAll();
    }

    @Override
    public BSResult updateRole_User(int userId, int[] roleIds) {

         for(int roleId:roleIds){
             UserRole userRole=new UserRole();
             userRole.setUser_id(userId);
             userRole.setRole_id(roleId);
             userRole.setCreated(new Date());
             userRole.setUpdated(new Date());
            userRoleMapper.insert(userRole);
         }


        return BSResultUtils.success();
    }


    @Override
    public void deleteRole_User(int userId) {

            Example example = new Example(UserRole.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("user_id", userId);
            userRoleMapper.deleteByExample(example);

    }

    @Override
    public int addRole(Role role) {
        role.setCreated(new Date());
        role.setUpdated(new Date());
        return roleMapper.insert(role);
    }

    @Override
    public int deleteByRoleId(Integer roleId) {

        return roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public Role findRoleById(Integer roleId) {
        return roleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public int updateRole(Role role) {
        role.setUpdated(new Date());
        return roleMapper.updateByPrimaryKeySelective(role);
    }
}
